<?php
/**
 * 我的订单
 *
 *
 *
 *
 * @copyright  Copyright (c) 2007-2013 BesonIT Inc. (http://www.besonit.com)
 * @license    http://www.besonit.com
 * @link       http://www.besonit.com
 * @since      File available since Release v1.1
 */


defined('BYshopJL') or exit('Access Invalid!');

class member_orderControl extends wxMemberControl
{

    private $model_order;

    public function __construct()
    {
        parent::__construct();
        $this->model_order = Model('wx_order');
        Tpl::setDir('member');
    }

    /**
     * 订单列表
     */
    public function order_listOp()
    {
        $condition = array();
        $condition['buyer_id'] = $this->member_info['member_id'];

        $order_list_array = $this->model_order->getNormalOrderList($condition, $this->page, '*', 'order_id desc', '', array('order_goods'));

        $order_group_list = array();
        $order_pay_sn_array = array();
        foreach ($order_list_array as $value) {
            //显示取消订单
            $value['if_cancel'] = $this->model_order->getOrderOperateState('buyer_cancel', $value);
            //显示收货
            $value['if_receive'] = $this->model_order->getOrderOperateState('receive', $value);
            //显示锁定中
            $value['if_lock'] = $this->model_order->getOrderOperateState('lock', $value);
            //显示物流跟踪
            $value['if_deliver'] = $this->model_order->getOrderOperateState('deliver', $value);

            //商品图
            foreach ($value['extend_order_goods'] as $k => $goods_info) {
                $value['extend_order_goods'][$k]['goods_image_url'] = cthumb($goods_info['goods_image'], 240, $value['store_id']);
            }

            $order_group_list[$value['pay_sn']]['order_list'][] = $value;

            //如果有在线支付且未付款的订单则显示合并付款链接
            if ($value['order_state'] == ORDER_STATE_NEW) {
                $order_group_list[$value['pay_sn']]['pay_amount'] += $value['order_amount'] - $value['rcb_amount'] - $value['pd_amount'];
            }
            $order_group_list[$value['pay_sn']]['add_time'] = $value['add_time'];
            $order_group_list[$value['pay_sn']]['pay_name'] = $value['payment_code'];


            //记录一下pay_sn，后面需要查询支付单表
            $order_pay_sn_array[] = $value['pay_sn'];
        }

        $new_order_group_list = array();
        foreach ($order_group_list as $key => $value) {
            $value['pay_sn'] = strval($key);
            $new_order_group_list[] = $value;
        }

        $page_count = $this->model_order->gettotalpage();
//        echo "<pre>";
//        var_export($new_order_group_list);exit;
//        $curpage = isset($_GET['curpage']) && !empty($_GET['curpage']) ? intval($_GET['curpage']) : 1;
//        Tpl::output('pageSet', mobile_page($page_count));
//        Tpl::output('curpage', $curpage);
//        Tpl::output('order_group_list',$new_order_group_list);
//        Tpl::showpage('order_list', 'member_layout');
        output_data(array('order_group_list' => $new_order_group_list), mobile_page($page_count));
    }

    /**
     * 取消订单
     */
    public function order_cancelOp()
    {
        $logic_order = Logic('order');
        $order_id = intval($_POST['order_id']);

        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $this->member_info['member_id'];
        $order_info = $this->model_order->getOrderInfo($condition);
        $if_allow = $this->model_order->getOrderOperateState('buyer_cancel', $order_info);
        if (!$if_allow) {
            output_error('无权操作');
        }

        $result = $logic_order->changeOrderStateCancel($order_info, 'buyer', $this->member_info['member_name'], '其它原因');
        if (!$result['state']) {
            output_error($result['msg']);
        } else {
            output_data('1');
        }
    }

    /**
     * 订单确认收货
     */
    public function order_receiveOp()
    {
        $this->model_order = Model('wx_order');
        $logic_order = Logic('order');
        $order_id = intval($_POST['order_id']);

        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $this->member_info['member_id'];
        $order_info = $this->model_order->getOrderInfo($condition);
        $if_allow = $this->model_order->getOrderOperateState('receive', $order_info);
        if (!$if_allow) {
            output_error('无权操作');
        }

        $result = $logic_order->changeOrderStateReceive($order_info, 'buyer', $this->member_info['member_name']);
        if (!$result['state']) {
            output_error($result['msg']);
        } else {
            output_data('1');
        }
    }

    /**
     * 物流跟踪
     */
    public function search_deliverOp()
    {
        $order_id = intval($_POST['order_id']);
        if ($order_id <= 0) {
            output_error('订单不存在');
        }

        $this->model_order = Model('wx_order');
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $this->member_info['member_id'];
        $order_info = $this->model_order->getOrderInfo($condition, array('order_common', 'order_goods'));
        if (empty($order_info) || !in_array($order_info['order_state'], array(ORDER_STATE_SEND, ORDER_STATE_SUCCESS))) {
            output_error('订单不存在');
        }

        $express = rkcache('express', true);
        $e_code = $express[$order_info['extend_order_common']['shipping_express_id']]['e_code'];
        $e_name = $express[$order_info['extend_order_common']['shipping_express_id']]['e_name'];

        $deliver_info = $this->_get_express($e_code, $order_info['shipping_code']);
        output_data(array('express_name' => $e_name, 'shipping_code' => $order_info['shipping_code'], 'deliver_info' => $deliver_info));
    }



    /*
     * 订单详情
     */

    public function order_infoOp()
    {
        $pay_sn = $_POST['pay_sn'];
        $key = $_POST['key'];
        if(!$pay_sn) output_error('支付码错误');
        if(!$key)  output_error('用户信息错误');

        $mb_token = Model('mb_user_token')->getMbUserTokenInfoByToken($key);
        if(!$mb_token) output_error('token错误');
        if($mb_token['member_id'] != $this->member_info['member_id']) output_error('用户信息错误');

        $condition = array();
        $condition['pay_sn'] = $pay_sn;
        $condition['buyer_id'] = $this->member_info['member_id'];

        $order_info = $this->model_order->getOrderInfo($condition);
        if(!$order_info)  output_error('订单信息错误');
        $order_info_goods = $this->model_order->getOrderGoodsList(array('order_id'=>$order_info['order_id']));
        foreach($order_info_goods as $k=>$v){
            $order_info_goods[$k]['goods_image_url'] = cthumb($v['goods_image'], 240, $v['store_id']);
        }
        $order_info['goods_list'] = $order_info_goods;
        //发起微信支付
        $pay_param = self::create_wxpay_param($order_info);
        $order_info['pay_param'] = json_decode($pay_param);

        output_data(array('order_info' => $order_info));
    }


    private function create_wxpay_param($order_info){
        include_once(API_PATH."/payment/wxpay/WxPayPubHelper/WxPayPubHelper.php");

        $jsApi = new JsApi_pub();

        $openid = $this->member_info['member_wxopenid'];
        $out_trade_no = $order_info['pay_sn'];
        $total_fee = floatval($order_info['order_amount'])*100;//转换为分
        //使用统一支付接口
        $unifiedOrder = new UnifiedOrder_pub();

        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid","$openid");//商品描述
        $unifiedOrder->setParameter("body","商品描述");//商品描述

        $unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号
        $unifiedOrder->setParameter("total_fee","$total_fee");//总金额
        $unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID

        $prepay_id = $unifiedOrder->getPrepayId();
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);

        $jsApiParameters = $jsApi->getParameters();
        return $jsApiParameters;
    }

    /**
     * 从第三方取快递信息
     *
     */
    public function _get_express($e_code, $shipping_code)
    {

        $url = 'http://www.kuaidi100.com/query?type=' . $e_code . '&postid=' . $shipping_code . '&id=1&valicode=&temp=' . random(4) . '&sessionid=&tmp=' . random(4);
        import('function.ftp');
        $content = dfsockopen($url);
        $content = json_decode($content, true);

        if ($content['status'] != 200) {
            output_error('物流信息查询失败');
        }
        $content['data'] = array_reverse($content['data']);
        $output = array();
        if (is_array($content['data'])) {
            foreach ($content['data'] as $k => $v) {
                if ($v['time'] == '') continue;
                $output[] = $v['time'] . '&nbsp;&nbsp;' . $v['context'];
            }
        }
        if (empty($output)) exit(json_encode(false));
        if (strtoupper(CHARSET) == 'GBK') {
            $output = Language::getUTF8($output);//网站GBK使用编码时,转换为UTF-8,防止json输出汉字问题
        }

        return $output;
    }

}
